<template>
  <div id="info">
    <h1>this is avatar</h1>
    <el-upload
      class="avatar-uploader"
      ref="upload"
      action="#"
      :auto-upload="false"
      :show-file-list="false"
      :http-request="submitAvatar"
      :on-change="previewAvatar"
      :before-upload="beforeAvatarUpload">
      <img v-if="avatarUrl" :src="avatarUrl" alt="not find" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
    <el-button size="small" type="primary" @click="submit">点击上传</el-button>
  </div>
</template>

<script>
  import avatar from '../../api/avatar/avatar'
  import store from '../../store'
  import user from '../../store/modules/user'
  export default {
    name: 'info',
    data(){
      return{
        avatarUrl:'',
        file:{}
      }
    },
    created() {
      this.avatarUrl = store.getters.avatar
    },
    methods:{
      previewAvatar(file){
        this.avatarUrl = URL.createObjectURL(file.raw)
        this.file = file.raw
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      submitAvatar(){
        var formData = new FormData()
        formData.append("file",this.file)
        avatar.uploadAvatar(formData).then(res=>{
          user.state.avatar = this.avatarUrl
          this.$message.success("上传成功")
        })
      },
      submit(){
        this.submitAvatar()
      }
    }
  }
</script>

<style scoped>

  .avatar-uploader  {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader{
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
